package com.yuanhua.xcxmng.wechat.service.impl;

import com.yuanhua.xcxmng.wechat.entity.User;
import com.yuanhua.xcxmng.wechat.entity.UserDevice;
import com.yuanhua.xcxmng.wechat.entity.UserDeviceExample;
import com.yuanhua.xcxmng.wechat.mapper.UserDeviceMapper;
import com.yuanhua.xcxmng.wechat.service.UserDeviceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author hzy24985
 * @version $Id: UserDeviceServiceImpl, v 0.1 2018/8/14 下午2:14 hzy24985 Exp $
 */
@Service
public class UserDeviceServiceImpl implements UserDeviceService {

    @Resource
    private UserDeviceMapper userDeviceMapper;

    @Override
    public int saveDeviceLink(String deviceId, User user) {
        UserDevice userDevice = new UserDevice();
        UserDeviceExample example = new UserDeviceExample();
        example.createCriteria().andOpenIdEqualTo(user.getOpenId());
        List<UserDevice> userDevices = userDeviceMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(userDevices)) {
            Optional<UserDevice> optional = userDevices.stream().filter(d -> StringUtils.equalsIgnoreCase(d.getDeviceId(), deviceId)).findFirst();
            if (optional.isPresent()) {
                UserDevice curr = optional.get();
                curr.setBinding(1);
                return userDeviceMapper.updateByPrimaryKey(curr);
            }
        }

        userDevice.setCreateTime(new Date());
        userDevice.setDeviceId(deviceId);
        userDevice.setOpenId(user.getOpenId());
        userDevice.setUnionId(user.getUnionId());
        userDeviceMapper.insert(userDevice);
        return 0;
    }

    @Override
    public void relieveLink(String deviceId, User user) {
        UserDeviceExample example = new UserDeviceExample();
        example.createCriteria().andOpenIdEqualTo(user.getOpenId());
        List<UserDevice> userDevices = userDeviceMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(userDevices)) {
            Optional<UserDevice> optional = userDevices.stream().filter(d -> StringUtils.equalsIgnoreCase(d.getDeviceId(), deviceId)).findFirst();
            if (optional.isPresent()) {
                UserDevice curr = optional.get();
                curr.setBinding(0);
                userDeviceMapper.updateByPrimaryKey(curr);
            }
        }
    }

    @Override
    public String getBindingDeviceIdByOpenId(String openId) {
        UserDeviceExample example = new UserDeviceExample();
        example.createCriteria().andOpenIdEqualTo(openId)
        .andBindingEqualTo(1);
        List<UserDevice> userDevices = userDeviceMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(userDevices)) {
            return StringUtils.EMPTY;
        }

        return userDevices.get(0).getDeviceId();
    }
}
